package com.vecspace.utils;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.persistence.Column;


public class AnnoUtil {
	
	private static Map<String, String> propColumnAnnoMap = new ConcurrentHashMap<>(1024);
	/**根据属性名获取字段名（根据getter上的@Column注解获取）
	 * @param clazz
	 * @param propName
	 * @return 
	 * @author wanghua
	 */
	public static String getColumnNameByPropName(Class<?> clazz, String propName) {
		String cacheKey = clazz.getName()+"."+propName;
		String columnName = propColumnAnnoMap.get(cacheKey);
		if(columnName != null) return columnName;
		
		String propName0 = propName.substring(0, 1).toUpperCase() + propName.substring(1);
		String propName1 = "get" + propName0;
		String propName2 = "is" + propName0;
		Method[] methods = clazz.getMethods();
		for(Method method : methods) {
			String methodName = method.getName();
			if(methodName.equals(propName1) || methodName.equals(propName2)) {
				if(method.getParameterCount() == 0) {
					Column column = method.getDeclaredAnnotation(Column.class);
					if(column != null) {
						columnName = column.name();
						propColumnAnnoMap.put(cacheKey, columnName);
						return columnName;
					}
					break;
				}
			}
		}
		return null;
	}
}
